<?php

namespace App\Http\Controllers\Webdisk;

use App\Http\Controllers\Controller;
use App\Webdisk\Model\FileCache;
use App\Webdisk\Model\LogInfo;
use App\Webdisk\Model\StatInfo;
use Illuminate\Http\Request;

use function App\Webdisk\makeRes;

class ResourceController extends Controller
{
    function search(Request $req){
        $req->validate([
            'key'=>['required']
        ]);
        $cache_stat = StatInfo::get("cache_stat");
        if( $cache_stat != 'ok' ){
            LogInfo::add("[文件搜索]因缓存处于{$cache_stat}状态被拒绝 关键词：".$req->input('key'), $_SERVER['REMOTE_ADDR'], LOG_LEVEL_WARNING);
            return makeRes(-4,null,'缓存正在更新/创建，搜索暂时不可用');
        }
        $key = str_replace(' ','%',$req->input('key'));
        $begin = microtime(true);
        $limit_path = $req->input('path');
        $pre_page_max = $req->input("pre_page_max",15);
        if ( $limit_path != null ){
            $primary_data = FileCache::where([
                ['name','like',"%$key%"],
                ['path', 'like', "%$limit_path%"]
            ])->paginate($pre_page_max);
        }else{
            $primary_data = FileCache::where('name','like',"%$key%")->paginate($pre_page_max);
        }
        $res = [
            'key' => $req->input('key'),
            'time'=> microtime(true) - $begin,
            'total'=>$primary_data->total(),
            'last_page'=>$primary_data->lastPage(),
            'current_page'=>$primary_data->currentPage(),
            'last_make_cache'=>(int)StatInfo::get('last_make_cache'),
            'data'=>$primary_data->items()
        ];
        return makeRes(1,$res);
    }

    function list(Request $req)
    {
        $req->validate([
            'path'=>['required','not_regex:/\.\./']
        ]);
        $physic_prefix = env('RES_ROOT');
        try {
            $dir_data = scandir($physic_prefix.'/'.$_POST['path']);
        } catch (\Throwable $th) {
            return makeRes(-2,null,"无效路径");
        }
        $data = [];
        array_shift($dir_data);array_shift($dir_data);
        $dirs = [];
        $files = [];
        foreach ($dir_data as $key => $value) {
            $t = [
                'name'=>$value
            ];
            $physic_path = "$physic_prefix/{$_POST['path']}/".$value;
            $t['date'] = filemtime($physic_path);
            if(is_file($physic_path)){
                $t['type'] = 'file';
                $t['size'] = filesize($physic_path);
                $files[] = $t;
            }else{
                $t['type'] = 'dir';
                $t['size'] = '-';
                $dirs[] = $t;
            }
        }
        $data = [
            'dirs'=>$dirs,
            'files'=>$files
        ];
        return makeRes(1,$data);
    }
}
